package org.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.example.mapper.SeckillActivityMapper;
import org.example.domain.SeckillActivity;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
public class RedisStockConfig {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate; // 直接注入已存在的Bean

    @Autowired
    private SeckillActivityMapper seckillActivityMapper;

    @PostConstruct
    public void initStockOnStartup() {
        initStock();
    }

    public void initStock() {
        // 查询出活动信息表所有活动
        List<SeckillActivity> activities = seckillActivityMapper.selectList(null);

        if (activities != null && !activities.isEmpty()) {
            for (SeckillActivity activity : activities) {
                // 获取活动ID和库存
                Long activityId = activity.getActivityId();
                Integer availableStock = activity.getAvailableStock();

                // 构造库存key
                String stockKey = "seckill:stock:" + activityId;

                // 修改：直接存储整数类型，而不是转换为字符串
                redisTemplate.opsForValue().set(stockKey, availableStock, 60, TimeUnit.MINUTES);

                System.out.println("已向Redis写入库存数据: key=" + stockKey + ", value=" + availableStock);
            }
            System.out.println("总共初始化了 " + activities.size() + " 个活动的库存数据");
        } else {
            System.out.println("未找到任何秒杀活动");
        }
    }


}
